/**
 * 
 */
package com.android.dwt.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ZoomControls;

import com.android.dwt.MyLocationManager;
import com.android.dwt.Position;
import com.android.dwt.R;
import com.android.dwt.R.drawable;
import com.android.dwt.R.id;
import com.android.dwt.R.layout;
import com.android.dwt.data.GTDApp;
import com.android.dwt.util.C;
import com.android.dwt.util.Utils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;

/**
 * @author xiang
 *
 */
public class MapManagerAct extends MapActivity
		implements OnClickListener, DialogInterface.OnClickListener {
		
	private final String TAG = "AddPositionAct";
	public static String TREASURE_PROXIMITY_ALERT = "com.android.dwt.PosAlert";
	private static final int MENU_ORIENTATE = 0;
//		private final String mLocProvider = LocationManager.GPS_PROVIDER;
	
	private LayoutInflater mInflater;
	private MapView mMapView;
	private MapController mMapCtrlr;
	private GeoPoint mCenter;
//	private LocationManager mLocationMgr;
//	private Location mCurLocation;			// user's current location
//	private Location mLastLocation;
	private View mPopView;
	private GTDApp mGa;
	private String mStrAddress;
	private int[] mLatLng = new int[2];		// lantitue and longtitude of current location
	private List<Overlay> mOverlays;
	private MyItemizedOverlay mMIO;
	private RelativeLayout mPopup;
	private ZoomControls mZoomCtrl;
	private int mZoomLevel;
//	private OverlayItem mCurrent;
//	private float mAlertRadius = 1000f;
//	private MyReceiver mReceiver;
	private MyLocationOverlay mMyLocationOverlay;
//	private TextProgress mProgressBar;
	private ProgressDialog mProgressDlg;
	private MyLocationManager mMyLocationMgr;
	
	private final Handler mHandler = new Handler() {
		
		@Override
		public void handleMessage(Message msg) {
				
				mProgressDlg.cancel();
				mProgressDlg = null;
				
				mFixRun = false;
		}
		
	};
	
	private boolean mFixRun;
	
		
    /**
     * The Class MapOverlay which customizes overlay.
     */
    /*private class MapOverlay extends com.google.android.maps.Overlay {
			
		@Override
		public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
            super.draw(canvas, mapView, shadow);                   
 
            //---translate the GeoPoint to screen pixels---
            Point screenPts = new Point();
            mapView.getProjection().toPixels(mCenter, screenPts);
 
            //---add the marker---
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);            
            canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
            
            return true;
        }
	        
	        @Override
	        public boolean onTouchEvent(MotionEvent event, MapView mapView) {
	            //---when user lifts his finger---
	            if (event.getAction() == MotionEvent.ACTION_UP) {
	            	
	            	// add a view to display current location
//	            	mPopView.setVisibility(View.VISIBLE);
	            	
	                GeoPoint p = mapView.getProjection()
	                		.fromPixels((int) event.getX(), (int) event.getY());
	                mLatLng[0] = p.getLatitudeE6();		// latitude
	                mLatLng[1] = p.getLongitudeE6();	// longtitude
	                
	                mStrAddress = getAddressByLatLng(mLatLng[0]/1e6, mLatLng[1]/1e6);
	                
	                // set the popup
	                MapView.LayoutParams geoLP = (MapView.LayoutParams) mPopView.getLayoutParams();  
	                geoLP.point = p;
	                mapView.updateViewLayout(mPopView, geoLP);  
	                mPopView.setVisibility(View.VISIBLE);
	                
	                RelativeLayout button = (RelativeLayout) mPopView.findViewById(R.id.map_bubblebtn);
	    			button.setOnClickListener(AddPositionAct.this);
	                
	                TextView title = (TextView) mPopView.findViewById(R.id.map_bubbleTitle);  
	                TextView text = (TextView) mPopView.findViewById(R.id.map_bubbleText);  
	                title.setText("添加这个位置");  
	                text.setText(mStrAddress);  
	                
//	                Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	                
	                try {
	                	String address = getAddressByLatLng(p.getLatitudeE6()/1e6,
	                			p.getLongitudeE6()/1e6);
	                	
	                	Log.e(TAG, "touched address is: "+address);
	                	
	                	Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
	                	
	                    List<Address> addresses = geoCoder.getFromLocation(
	                        p.getLatitudeE6()/1E6, 
	                        p.getLongitudeE6()/1E6, 1);
	                    
	                    Log.e(TAG, "addresses size is: " + addresses.size());
	                    for (int i=0; i<addresses.size(); i++) {
	                    	String addr = "";
	                    	
	                    	for (int j=0; j<addresses.get(i).getMaxAddressLineIndex(); j++)
	                            addr += addresses.get(i).getAddressLine(j) + "\n";
	                    	
	                    	Log.e(TAG, "address["+i+"]: " + addr);
	                    }
	 
	                    String addr = "";
	                    if (addresses.size() > 0) {
	                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
	                           addr += addresses.get(0).getAddressLine(i) + "\n";
	                            
	                        
	                    	Toast.makeText(getBaseContext(), addr, Toast.LENGTH_SHORT).show();
	                    }
	 
	                    
	                } catch (Exception e) {                
	                    e.printStackTrace();
	                }
	                
	                return true;
	            }
	            
	            return false;
	        }  
	    }*/
		
		/**
		 * The Class MyItemizedOverlay.
		 */
		private class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
			
			private List<OverlayItem> GeoList = new ArrayList<OverlayItem>();
	    	private Drawable marker;
	    	
	    	
			public MyItemizedOverlay(Drawable defaultMarker) {
				super(defaultMarker);
				
				// TODO Auto-generated constructor stub
				MyItemizedOverlay.this.marker = marker;
				
				ArrayList<Position> al = mGa.getPositions();
				int size = al.size();
				
				for (int i=1; i<size; i++) {		// only mark items with latitude and longtitude
					GeoPoint p = new GeoPoint(al.get(i).getLatitude(), al.get(i).getLongtitude());
					GeoList.add(new OverlayItem(p, al.get(i).getPlace(), al.get(i).getAddress()));
				}
				
				this.populate();
				
			}
			
			/*@Override
			public boolean onTouchEvent(MotionEvent event, MapView mapView) {
				// TODO Auto-generated method stub
				
				if (event.getAction() == MotionEvent.ACTION_UP) {
	            	
	            	// add a view to display current location
//	            	mPopView.setVisibility(View.VISIBLE);
	            	
	                GeoPoint p = mapView.getProjection()
	                		.fromPixels((int) event.getX(), (int) event.getY());
	                mLatLng[0] = p.getLatitudeE6();		// latitude
	                mLatLng[1] = p.getLongitudeE6();	// longtitude
	                
	                mStrAddress = getAddressByLatLng(mLatLng[0]/1e6, mLatLng[1]/1e6);
	                
	                // set the popup
	                MapView.LayoutParams geoLP = (MapView.LayoutParams) mPopView.getLayoutParams();  
	                geoLP.point = p;
	                mapView.updateViewLayout(mPopView, geoLP);  
	                mPopView.setVisibility(View.VISIBLE);
	                
	                RelativeLayout button = (RelativeLayout) mPopView.findViewById(R.id.map_bubblebtn);
	    			button.setOnClickListener(AddPositionAct.this);
	                
	                TextView title = (TextView) mPopView.findViewById(R.id.map_bubbleTitle);  
	                TextView text = (TextView) mPopView.findViewById(R.id.map_bubbleText);  
	                title.setText("添加该位置");  
	                text.setText(mStrAddress);  
	                
//	                Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
	                
	                try {
	                	String address = getAddressByLatLng(p.getLatitudeE6()/1e6,
	                			p.getLongitudeE6()/1e6);
	                	
	                	Log.e(TAG, "touched address is: "+address);
	                	
	                	Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
	                	
	                    List<Address> addresses = geoCoder.getFromLocation(
	                        p.getLatitudeE6()/1E6, 
	                        p.getLongitudeE6()/1E6, 1);
	                    
	                    Log.e(TAG, "addresses size is: " + addresses.size());
	                    for (int i=0; i<addresses.size(); i++) {
	                    	String addr = "";
	                    	
	                    	for (int j=0; j<addresses.get(i).getMaxAddressLineIndex(); j++)
	                            addr += addresses.get(i).getAddressLine(j) + "\n";
	                    	
	                    	Log.e(TAG, "address["+i+"]: " + addr);
	                    }
	 
	                    String addr = "";
	                    if (addresses.size() > 0) {
	                        for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
	                           addr += addresses.get(0).getAddressLine(i) + "\n";
	                            
	                        
	                    	Toast.makeText(getBaseContext(), addr, Toast.LENGTH_SHORT).show();
	                    }
	 
	                    
	                } catch (Exception e) {                
	                    e.printStackTrace();
	                }
	                
	                return true;
	            }

				return false;
			}*/
			
			@Override
			public void draw(Canvas canvas, MapView mapView, boolean shadow) {
				// TODO Auto-generated method stub
				
		        Projection projection = mapView.getProjection();
		        for (int i=0; i<GeoList.size(); i++) {
		            OverlayItem overLayItem = getItem(i);
		            String title = overLayItem.getTitle();
		            
		            if (title == null)
		            	continue;
		            
		            // 把经纬度变换到相对于MapView左上角的屏幕像素坐标 
		            Point point = projection.toPixels(overLayItem.getPoint(), null);
//		            canvas.drawBitmap(bmp, pos.x + deviation.x, pos.y + deviation.y, null);
		            
		            //---translate the GeoPoint to screen pixels---
//		            Point screenPts = new Point();
//		            mapView.getProjection().toPixels(mCenter, screenPts);
		 
		            //---add the marker---
		            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pushpin);            
		            canvas.drawBitmap(bmp, point.x, point.y-5, null);

		            /*Paint paintCircle = new Paint();  
		            paintCircle.setColor(Color.RED);  
		            canvas.drawCircle(point.x, point.y, 5, paintCircle); // 画圆 
	*/	            
		            /*Paint paintText = new Paint();  
		            paintText.setColor(Color.BLACK);  
		            paintText.setTextSize(15);*/
		            
		        }

			}
			
			/*public void insertCurLocation(OverlayItem o) {
				GeoList.add(o);		// insert at the end of the list
				populate();
			}*/
			
			public void addOverlay(OverlayItem o) {
				GeoList.add(o);
//				setLastFocusedIndex(-1);
				populate();
			}

			public void removeOverlay(OverlayItem o) {
				GeoList.remove(o);
//				setLastFocusedIndex(-1);
				populate();
			}
			
			public void refresh() {
			    populate();
			}
			
			@Override
			protected OverlayItem createItem(int i) {
				// TODO Auto-generated method stub
				return GeoList.get(i);
				
//				return null;
			}

			@Override
			public int size() {
				// TODO Auto-generated method stub
				return GeoList.size();
				
//				return 0;
			}
			
			@Override
			protected boolean onTap(int index) {
				// TODO Auto-generated method stub
//				return super.onTap(index);
				
				OverlayItem oi = GeoList.get(index);
				GeoPoint gp = oi.getPoint();
				
				this.setFocus(oi);
				
				// set the popup
	            MapView.LayoutParams geoLP = (MapView.LayoutParams) mPopView.getLayoutParams();
	            geoLP.point = gp;
	            mMapView.updateViewLayout(mPopView, geoLP);
	            mPopView.setVisibility(View.VISIBLE);
	            
	            mPopup.setOnClickListener(null);
	            
	            TextView title = (TextView) mPopView.findViewById(R.id.map_bubbleTitle);
				TextView text = (TextView) mPopView.findViewById(R.id.map_bubbleText);
				title.setText(oi.getTitle());
				text.setText(oi.getSnippet());
	            
		        /*Toast.makeText(AddPositionAct.this,
		        		oi.getSnippet(),
		        		Toast.LENGTH_SHORT)
		        	.show();*/
		        
		        return true;
			}
			
			@Override
			public boolean onTap(GeoPoint p, MapView mapView) {
				// TODO Auto-generated method stub
				boolean tapped = super.onTap(p, mapView);
				
				if (tapped) {		// tap on a spicific overlay
					return true;
				}
				
				mLatLng[0] = p.getLatitudeE6(); 		// latitude
				mLatLng[1] = p.getLongitudeE6(); 		// longtitude

//				mStrAddress = getAddressByLatLng(mLatLng[0] / 1e6, mLatLng[1] / 1e6);
				mStrAddress = mMyLocationMgr.getAddressByLatLng(
						p.getLatitudeE6()/1e6, p.getLongitudeE6()/1e6);
				
				// set the popup
				MapView.LayoutParams geoLP = (MapView.LayoutParams) mPopView.getLayoutParams();
				geoLP.point = p;
				mapView.updateViewLayout(mPopView, geoLP);
				mPopView.setVisibility(View.VISIBLE);

				mPopup.setOnClickListener(MapManagerAct.this);

				TextView title = (TextView) mPopView.findViewById(R.id.map_bubbleTitle);
				TextView text = (TextView) mPopView.findViewById(R.id.map_bubbleText);
				title.setText("添加该位置");
				text.setText(mStrAddress);

				return true;
			}
			
		}	// class ends here
		
		
		@Override
		protected void onCreate(Bundle savedInstanceState) {
			// TODO Auto-generated method stub
			super.onCreate(savedInstanceState);
			
			Log.e(TAG, "onCreate is called!");
			
			setContentView(R.layout.pos_add_location);
			
			initViews();
			
		}
		
		@Override
		protected void onPause() {
			// TODO Auto-generated method stub
			super.onPause();
			
		}
		
		@Override
		protected void onStop() {
			// TODO Auto-generated method stub
			
			Log.e(TAG, "onStop is called!");
		    
			mMyLocationOverlay.disableMyLocation();
			
//			mLocationMgr.removeUpdates(this);
//			mLocationMgr = null;
			
			super.onStop();
		}
		
		@Override
		protected void onResume() {
			// TODO Auto-generated method stub
			super.onResume();
			
			Log.e(TAG, "onResume is called!");
			
			mMyLocationOverlay.enableMyLocation();
		}
		
		@Override
		protected void onDestroy() {
			// TODO Auto-generated method stub
			
			Log.e(TAG, "onDestroy is called!");
			
			// Save states
			mGa.mMapCenter = mMapView.getMapCenter();
			mGa.mZoomLevel = mMapView.getZoomLevel();
			
			super.onDestroy();
		}
		
		/**
		 * Inits the views.
		 */
		private void initViews() {
			
			mGa = (GTDApp) getApplication();
//			mLocationMgr = mMyLocationMgr.getLocationManager();
			mCenter = mGa.mMapCenter;
			mZoomLevel = mGa.mZoomLevel;
			
			mMyLocationMgr = new MyLocationManager(this);
			
//			mProgressBar = (TextProgressBar) findViewById(R.id.pb_bar);
			mProgressDlg = new ProgressDialog(MapManagerAct.this);
			mProgressDlg.setMessage(" 正在定位中... ");
			mProgressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDlg.setCancelable(true);
			mProgressDlg.show();
			
			mMapView = (MapView) findViewById(R.id.mapView);
			mMapView.setSatellite(false);
			mMapView.setStreetView(false);
//			mMapView.setBuiltInZoomControls(true);
			
			mMapCtrlr = mMapView.getController();
	        mMapCtrlr.setZoom(mZoomLevel);
	        mMapCtrlr.animateTo(mCenter);
//	        mMapCtrlr.setCenter(mCenter);
			
	        // Set zoom control
			mZoomCtrl = (ZoomControls) findViewById(R.id.zoom_controls);
			mZoomCtrl.setOnZoomInClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mMapCtrlr.zoomIn();
				}
			});
			mZoomCtrl.setOnZoomOutClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					mMapCtrlr.zoomOut();
				}
			});

			mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
			mMyLocationOverlay.runOnFirstFix(new Runnable() {
				
				@Override
				public void run() {
					
					GeoPoint point = mMyLocationOverlay.getMyLocation();
					mMapCtrlr.animateTo(point);
					
					Log.e(TAG, "onCreate: locate map center" + " to " + "(" + point.getLatitudeE6()/1e6+
							", "+point.getLongitudeE6()/1e6+")");
					
					mHandler.sendEmptyMessage(0);
				}
				
			});
			mFixRun = true;
    			
	        
	        // initialize pop view
			mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
			mPopView = (View) mInflater.inflate(R.layout.overlay_pop, null);
	        mMapView.addView(
	        		mPopView,
	        		new MapView.LayoutParams(
	        				MapView.LayoutParams.WRAP_CONTENT,
	        				MapView.LayoutParams.WRAP_CONTENT,
	        				null, 
	        				MapView.LayoutParams.BOTTOM_CENTER));
//	        views.add(mPopView);
			mPopView.setVisibility(View.GONE);
			mPopup = (RelativeLayout) mPopView.findViewById(R.id.map_bubblebtn);
	       
	        // listen to location change
//	        mLocationMgr.requestLocationUpdates(getBestProvider(), 5000, 5, this);
//	        mLocationMgr.addGpsStatusListener(this);
	        
	        initOverlays();
	        
	        
//	        mReceiver = new MyReceiver();
//	        IntentFilter filter = new IntentFilter(TREASURE_PROXIMITY_ALERT);
//	        registerReceiver(mReceiver, filter); 
		}
		
		/**
		 * Inits the overlay item.
		 */
		private void initOverlays() {
			Drawable marker = getResources().getDrawable(R.drawable.pushpin);
	        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
	        
			// ---Add a location marker---
	        mMIO = new MyItemizedOverlay(marker);
	        /*mCurrent = new OverlayItem(mCenter,
	        		getString(R.string.cur_pos),
	        		getAddressByLatLng(mCenter.getLatitudeE6()/1e6, mCenter.getLongitudeE6()/1e6));*/
//	        mMIO.insertCurLocation(mCurrent);
	        
			mOverlays = mMapView.getOverlays();
			mOverlays.clear();
			mOverlays.add(mMIO);
			mOverlays.add(mMyLocationOverlay);
			
	        mMapView.invalidate();
	        
	        // for test
	        /*ArrayList<Position> al = mGa.getPositions();
	        for (int i=0; i<al.size(); i++) {
	        	setProximityAlert(al.get(i));
	        }*/
			        
	    }
		
		/*private void setProximityAlert(Position pos) {
			int lat = pos.getLatitude();
			int lng = pos.getLongtitude();
			
			mLastLocation = mLocationMgr.getLastKnownLocation(getBestProvider());
			if (mLastLocation == null) {
				Log.e(TAG, "location is null!");
				
				Toast.makeText(this, "获取位置失败", Toast.LENGTH_LONG).show();
				return;
			}
			
			Intent intent = new Intent(MapManagerAct.this, MyReceiver.class);
			intent.setAction(TREASURE_PROXIMITY_ALERT);
			PendingIntent proximityIntent = PendingIntent.getBroadcast(this,
					0,
					intent,
					PendingIntent.FLAG_UPDATE_CURRENT);
			mLocationMgr.addProximityAlert(lat/1e6, lng/1e6, mAlertRadius, -1, proximityIntent);
//			sendBroadcast(intent);
		}*/
		
		@Override
		protected boolean isRouteDisplayed() {
			// TODO Auto-generated method stub
			return false;
		}
		
		@Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			// TODO Auto-generated method stub
			
			MapController mc = mMapView.getController(); 
	        switch (keyCode) {
	        
	            case KeyEvent.KEYCODE_3:
	                mc.zoomIn();
	                break;
	                
	            case KeyEvent.KEYCODE_1:
	                mc.zoomOut();
	                break;
	               
	            default:
	            	break;
	        }
	        
			return super.onKeyDown(keyCode, event);
		}
		

		@Override
		public boolean onCreateOptionsMenu(Menu menu) {
			
			menu.add(0, MENU_ORIENTATE, Menu.NONE, "定位")
				.setIcon(android.R.drawable.ic_menu_mylocation);
			
			return super.onCreateOptionsMenu(menu);
		}
		
		@Override
		public boolean onOptionsItemSelected(MenuItem item) {
			
			switch(item.getItemId()) {
			
    			case MENU_ORIENTATE:
    				
    				mProgressDlg = new ProgressDialog(MapManagerAct.this);
    				mProgressDlg.setMessage(" 正在定位中... ");
    				mProgressDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    				mProgressDlg.setCancelable(true);
    				mProgressDlg.show();
    				
    				if (!mFixRun) {
    					
        				mMyLocationOverlay.runOnFirstFix(new Runnable() {
        					
        					@Override
        					public void run() {
        						
        						GeoPoint point = mMyLocationOverlay.getMyLocation();
        						mMapCtrlr.animateTo(point);
        						
        						Log.e(TAG, "menu: locate map center" + " to " + "(" + point.getLatitudeE6()/1e6+
        								", "+point.getLongitudeE6()/1e6+")");
        						
        						mHandler.sendEmptyMessage(0);
        					}
        					
        				});
        				
    				}
    				
    				break;
    				
    			default:
    				break;
			}
			
			return super.onOptionsItemSelected(item);
		}
		
		@Override
		public void onClick(View v) {
			
			switch (v.getId()) {
			
	    		case R.id.map_bubblebtn:
	    			
//	    			showDialog(DLG_ADD_LOCATION);
	    			LayoutInflater li = LayoutInflater.from(this);
	    		    View view = li.inflate(R.layout.prompt_view, null);
	    		    
	    		    ((TextView) view.findViewById(R.id.tv_prompt)).setHint(mStrAddress);
	    		    ((TextView) view.findViewById(R.id.et_prompt)).setHint("创建一个位置");
	    		   
	    		    AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    		    builder.setTitle("添加位置");
	    		    
	    		    builder.setView(view);
	    		    builder.setPositiveButton("确定", this);
	    		    builder.setNegativeButton("取消", this);
	    		    builder.create().show();  
	    			
	    			mPopView.setVisibility(View.GONE);
	    			
	    			break;
	    			
	    		default:
	    			break;
			}
		}
		
		/*@Override
		protected Dialog onCreateDialog(int id) {
			// TODO Auto-generated method stub
			Dialog dlg = null;
//			return super.onCreateDialog(id);
			
			switch (id) {
	    		case DLG_ADD_LOCATION:
	    			dlg = new Dialog(AddPositionAct.this);
	    			dlg.setContentView(R.layout.dialog_view);
	    			dlg.setTitle("添加该位置");
	    			dlg.show();
	    			
	    			break;
	    			
	    		default:
	    			break;
			}
			
			return dlg;
		}*/
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			
			AlertDialog ad = (AlertDialog) dialog;
			
			if(which == Dialog.BUTTON_POSITIVE) {
		        
		        EditText et = (EditText) ad.findViewById(R.id.et_prompt);
		        String pos = et.getText().toString();		// place name
		        
		        if (pos.length() == 0) {
		        	
		        	Utils.closeAlertDialog(ad, false);
		        	
		        	Toast.makeText(this, "地名不能为空", Toast.LENGTH_LONG).show();
		        	
		        	return;
		        }
		        
		        Position newPos = new Position(mStrAddress, pos, mLatLng[0], mLatLng[1]);
		        mGa.getPositions().add(newPos);
		        
		        // set alert of this place
//		        setProximityAlert(newPos);
		        
		        // write it into sharedPreferences
		        SharedPreferences sp = getSharedPreferences(GTDApp.strPosition, GTDApp.MODE);
		        Editor edit = sp.edit();
		        int count = sp.getInt("count", -1);
		        
		        if (pos.length() > 0) {
		        	edit.putString("Place["+count+"]", pos);
		        	
		        } else {
		        	edit.putString("Place["+count+"]", mStrAddress);
		        }
		        
		        edit.putString("Address["+count+"]", mStrAddress);
		        edit.putInt("Latitude["+count+"]", mLatLng[0]);
			    edit.putInt("Longtitude["+count+"]", mLatLng[1]);
		        edit.putInt("count", count+1);
		        
		        edit.commit();
		        
		        
		        /*Drawable marker = getResources().getDrawable(R.drawable.pushpin);
		        marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker.getIntrinsicHeight());
		        
		        mOverlays.clear();
		        mOverlays.add(new MyItemizedOverlay(marker));
		        mMapView.invalidate();*/
		        
//		        mOverlays.clear();
		        mMIO.addOverlay(new OverlayItem(new GeoPoint(mLatLng[0], mLatLng[1]), pos, mStrAddress));
//		        mOverlays.add(mMIO);
		        mMapView.invalidate();
		        
		        Toast.makeText(this, "添加位置成功", Toast.LENGTH_LONG).show();
		        
		        Utils.closeAlertDialog(ad, true);
		        
		        dialog.dismiss();
		        
		    } else if (which == Dialog.BUTTON_NEGATIVE) {
		    	
		    	Utils.closeAlertDialog(ad, true);
		    	
		    	dialog.dismiss();
		    }

		}
		
		@Override
		public void onBackPressed() {
			// TODO Auto-generated method stub
//			super.onBackPressed();
			
			setResult(RESULT_OK);
			finish();
		}

}
